//
//  EditAddressViewController.m
//  cliqset
//
//  Created by David Hinson on 2/19/09.
//  Copyright 2009 Sumner Systems Management, Inc.. All rights reserved.
//

#import "EditAddressViewController.h"
#import "cliqsetAppDelegate.h"
#import "Contact.h"

@implementation EditAddressViewController

@synthesize addressTypeField;
@synthesize streetField;
@synthesize localityField;
@synthesize regionField;
@synthesize postalCodeField;
@synthesize countryField;
@synthesize addresses;
@synthesize parent;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	self.title = @"Edit Address";
	
	self.addresses.backgroundColor = [UIColor clearColor];
	
	// Set save button
	UIBarButtonItem* saveButton = [[[UIBarButtonItem alloc] initWithTitle:@"Save" style:UIBarButtonItemStyleBordered target:self action:@selector(doSave:)] retain];
	self.navigationItem.rightBarButtonItem = saveButton;
	
	// Set cancel button
	UIBarButtonItem* cancelButton = [[[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(doCancel:)] retain];
	self.navigationItem.leftBarButtonItem = cancelButton;
}

// Do cancel
-(void)doCancel:(id)id {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	NSLog(@"doCancel");
	
	[myApp slideIMOut];
}

// Do save
-(void)doSave:(id)id {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	if ([self.streetField isEqualToString:@""]) {
		[myApp addTextToLog:@"Street Cannot Be Empty!" withCaption:@"Edit Address" ];
		return;
	}
	
	// Dereference our contact
	Contact *contact=nil; 
	if (self.parent.index>=0) {
	if (parent.isFavorite) {
		for (int x=0; x<[myApp.contacts count]; x++) {
			Contact *localContact = (Contact*)[myApp.contacts objectAtIndex:x]; 
			if ([localContact.contactIdentifier isEqualToString:[myApp.favorites objectAtIndex:parent.index]]) {
				contact = localContact;
				break;
			}
		}
	} 
	else {
		contact = (Contact *)[myApp.contacts objectAtIndex:parent.index];
	}
	} else {
		contact = self.parent.bufferContact;
	}
	
	NSLog(@"doSave");
	
	NSMutableString* strTag;
	if (parent.isPersonal) {
		strTag = @"Home";
	}
	else {
		strTag = @"Work";
	}
	
	// Add through cliqset, if editing
	if (self.parent.index>=0) {
		[myApp.cliqset putAddress:contact.contactIdentifier tag:strTag street:streetField locality:localityField region:regionField postalCode:postalCodeField country:countryField];
		}
	
	// And add back to contact im screen names array
	Address * address = [[Address alloc] init];
	
	// Build im entry
	// Street, Locality, Region, Postal Code, Country
	address.type           = strTag;
	address.streetAddress  = streetField;
	address.locality       = localityField;
	address.region         = regionField;
	address.postalCode     = postalCodeField;
	address.country        = countryField;
	address.primary        = YES;
	
	// Cycle through ims... we need to remove any existing with the same type
	for (int x=0; x<[contact.addresses count]; x++) {
		Address * ta = (Address*)[contact.addresses objectAtIndex:x];
		NSLog(@"%d  ta: [%@] - internal: [%@]", x, ta.type, strTag);
		if ([ta.type isEqualToString:strTag]) {
			[contact.addresses removeObjectAtIndex:x];
			break;
		}
	}
	
	[contact.addresses addObject:address];
	[address release];
	
	[myApp slideAddressOut];
	[parent.contactDetailTable reloadData];	
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}

// Number of table sections
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 2;
}

// Return rows in table
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	
	if (section == 0) {
		return 2;
		}

	if (section == 1) {
		return 1;
	}
	
	return 1;
}

// Set row height
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {	
	return 40.0;
}

// Indicate disclosure
- (UITableViewCellAccessoryType)tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath
{
	if (indexPath.section == 1 && indexPath.row == 0) {
		return UITableViewCellAccessoryDisclosureIndicator;	
	} 
	else {
		return UITableViewCellAccessoryNone;
	}
}

// Draw cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	UITableViewCell *cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:nil] autorelease];
    [cell backgroundView].opaque=YES;
    [cell backgroundView].clearsContextBeforeDrawing;
   	[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
	
	UIFont* small_font      = [UIFont systemFontOfSize:17];
	UIFont* large_font      = [UIFont systemFontOfSize:18];
	UIColor* textColor      = [UIColor colorWithRed:85.0/255.0 green:85.0/255.0 blue:85.0/255.0 alpha:1.0];
	
	cell.hidesAccessoryWhenEditing = NO;
	
	UITextField * street     = [[UITextField alloc] initWithFrame:CGRectMake(20,  10, 290, 40)];
	UITextField * locality   = [[UITextField alloc] initWithFrame:CGRectMake(20,  10, 160, 40)];
	UITextField * region     = [[UITextField alloc] initWithFrame:CGRectMake(190, 10, 50,  40)];
	UITextField * postalCode = [[UITextField alloc] initWithFrame:CGRectMake(250, 10, 50,  40)];
	UILabel * country        = [[UILabel alloc] initWithFrame:CGRectMake(20, 2 ,290, 38)];
	
	switch (indexPath.section) {
		case 0:
			switch (indexPath.row) {
				case 0:
			
					street.textColor   = textColor;
					street.font        = small_font;
					street.placeholder = @"Street";
			
					street.keyboardType = UIKeyboardTypeAlphabet;
					street.autocapitalizationType = UITextAutocapitalizationTypeWords;
					[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(streetDidChange:) name:@"UITextFieldTextDidChangeNotification" object:street];
					street.text         = (!self.streetField || [self.streetField isEqualToString:@""]) ? @"" : self.streetField;
			
					[street becomeFirstResponder];
			
					[cell addSubview:street];
			
					break;
			
				case 1:
			
					// locality (city)
					locality.textColor   = textColor;
					locality.font        = small_font;
					locality.placeholder = @"Locality";
			
					locality.keyboardType = UIKeyboardTypeAlphabet;
					locality.autocapitalizationType = UITextAutocapitalizationTypeWords;
					[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(localityDidChange:) name:@"UITextFieldTextDidChangeNotification" object:locality];
					locality.text         = (!self.localityField || [self.localityField isEqualToString:@""]) ? @"" : self.localityField;
			
					[cell addSubview:locality];

					// region (state)
					region.textColor   = textColor;
					region.font        = small_font;
					region.placeholder = @"State";
			
					region.keyboardType = UIKeyboardTypeAlphabet;
					region.autocapitalizationType = UITextAutocapitalizationTypeAllCharacters;
					region.autocorrectionType = UITextAutocorrectionTypeNo;
					[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(regionDidChange:) name:@"UITextFieldTextDidChangeNotification" object:region];
					region.text         = (!self.regionField || [self.regionField isEqualToString:@""]) ? @"" : self.regionField;
			
					[cell addSubview:region];
			
					// postal code
					postalCode.textColor   = textColor;
					postalCode.font        = small_font;
					postalCode.placeholder = @"Postal";
			
					postalCode.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
					postalCode.autocapitalizationType = UITextAutocapitalizationTypeAllCharacters;
					postalCode.autocorrectionType = UITextAutocorrectionTypeNo;
					[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(postalCodeDidChange:) name:@"UITextFieldTextDidChangeNotification" object:postalCode];
					postalCode.text         = (!self.postalCodeField || [self.postalCodeField isEqualToString:@""]) ? @"" : self.postalCodeField;
			
					[cell addSubview:postalCode];
			
					break;
				}
			break;
		case 1:
			// country
			country.textColor   = textColor;
			country.font        = large_font;			
			country.text        = (!self.countryField || [self.countryField isEqualToString:@""]) ? @"US" : self.countryField;
			self.countryField   = (NSMutableString*)country.text;
			
			[cell addSubview:country];
			break;
		}
	
	[street release];
	[locality release];
	[region release];
	[postalCode release];
	[country release];
	
	UIColor* myBGColor               = [UIColor colorWithRed:248.0/255.0 green:248.0/255.0 blue:248.0/255.0 alpha:1.0];
	cell.backgroundView.backgroundColor = myBGColor;
	for ( UIView* view in cell.contentView.subviews ) 
	{
		view.backgroundColor = [ UIColor clearColor ];
	}
	
	return cell;
}	

// Row selected... 
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {	
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	NSLog(@"didSelectRowAtIndexPath");
	
	UITableViewCell *hitCell = [tableView cellForRowAtIndexPath:indexPath];	
    [hitCell setSelected:NO animated:YES];
	
	if (indexPath.section == 1) {
		[myApp slideAddressTypeIn:self];
	}
}

// Our street changed... save it
-(void)streetDidChange:(id)textField {	
	self.streetField = (NSMutableString*)[[textField object] text];
}

// Our locality changed... save it
-(void)localityDidChange:(id)textField {	
	self.localityField = (NSMutableString*)[[textField object] text];
}

// Our region changed... save it
-(void)regionDidChange:(id)textField {	
	self.regionField = (NSMutableString*)[[textField object] text];
}

// Our postal code changed... save it
-(void)postalCodeDidChange:(id)textField {	
	self.postalCodeField = (NSMutableString*)[[textField object] text];
}

- (void)dealloc {

	[addressTypeField release];
	[streetField release];
	[localityField release];
	[regionField release];
	[postalCodeField release];
	[countryField release];
	[addresses release];
	[parent release];
	    
	[super dealloc];
}

@end
